package com.fits.gateway.api.filters;

import com.fits.gateway.api.contsants.AuthConstants;
import com.fits.gateway.api.props.IgnoreUrlProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.util.List;


/**
 * 白名单过滤器 清除token
 *
 * @author lzy
 * @since 11:05 2024/7/4
 */
@Component
public class IgnoreFilterConfig implements WebFilter {
    @Autowired
    private IgnoreUrlProperties ignoreUrlProperties;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        List<String> urls = ignoreUrlProperties.getUrls();
        for (String url : urls) {
            if (chechUrl(url, request)) {
                //修改接口，去除token
                request = request.mutate()
                        .header(AuthConstants.JWT_TOKEN_HEADER, "")
                        .header(AuthConstants.IGNORE_URL, "1")
                        .build();
                exchange.mutate().request(request).build();
                return chain.filter(exchange);
            }
        }
        return chain.filter(exchange);
    }

    private boolean chechUrl(String ignoreUrl, ServerHttpRequest request) {
        URI uri = request.getURI();
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        return antPathMatcher.match(ignoreUrl, uri.getPath());
    }


}
